<?php

namespace Sensio\Bundle\TrainingBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
//use Symfony\Component\HttpFoundation\Cookie;

class DefaultController extends Controller
{
    /**
     * @Route(
     *      path            = "/hello/{name}", 
     *      name            = "greet", 
     *      requirements    = {"name" = "[[:alpha:]]+"},
     *      host            = "formation-symfony.dev"
     * )
     */
    public function helloAction(Request $request,$name)
    {
//        $expires = new \DateTime('+30 days');
//        $cookie = new Cookie('username',$name,$expires);
        $session = $request->getSession();
        $session->set('username', $name);
        $response = $this->redirect($this->generateUrl("hello"));
//        $response->headers->setCookie($cookie);
        
        return $response;
    }
    
    /**
     * @Route(
     *      path            = "/hello", 
     *      name            = "hello"
     * )
     * @Template
     */
    public function indexAction(Request $request)
    {
       if(!$name = $request->getSession()->get('username'))
       {
           throw $this->createNotFoundException();
       }
       return array(
               'name'=>$name
       );
    }
    
    /**
     * 
     */
    public function counterAction()
    {
        return new Response(sprintf('%u people online',  mt_rand(0, 99999)));
    }
}

